package com.steamedfish.auctioncloudadserver.service.elasticsearch;


import com.steamedfish.auctioncloudadserver.entiry.AuctionRegisterEntity;
import com.steamedfish.auctioncloudadserver.model.AuctionItemModel;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.QueryBuilders;

import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ElasticSearchService {

    //以下是配置推广时间的参数

    private String TIME_1 = "08:00:00";

    private String TIME_2 = "19:59:00";

    private String TIME_LOW = "00:00:00";

    private String TIME_HIGH = "23:59:00";

    private Integer DEFAULT_PAGE_INDEX = 0;

    private Integer DEFAULT_PAGE_SIZE = 2;

    //以下是生成商品推广地址的参数

    @Value(value = "${auction.item.host:127.0.0.1}")
    private String AUCTION_HOST;

    @Value(value = "${auction.item.port:8080}")
    private String AUCTION_PORT;

    @Value(value = "${auction.item.url.prefix:http://}")
    private String HTTP_PREFIX;

    @Value(value = "${auction.item.url.path:/#/pages/index/auctionItemDetail/auctionItemDetail}")
    private String URI_PATH;

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    private String timePrefix = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));


    /**
     * 根据商品id数组查询商品信息
     *
     * @param id
     * @return int
     */
    public Map<String, String > searchByListId(List id){
        Map<String, String> map = new HashMap<>();
        for (int i = 0; i < id.size(); i++) {
            AuctionItemModel auctionItemModel = getAuctionItemModel((String) id.get(i));
            if (auctionItemModel != null && auctionItemModel.getDeleted().equals("0")) {
                map.put("商品名:" + auctionItemModel.getName() +
                                "  商品信息:" + (auctionItemModel.getDescription() == null ? "" : auctionItemModel.getDescription()) +
                                "  起拍价(最低价):" + (auctionItemModel.getLowerPrice() == null ? "未知" : auctionItemModel.getLowerPrice()),
                        "    商品连接:" + getAuctionURL(auctionItemModel.getId()));
            }
        }
        return map;
    }


    /**
     * 更具商品id铲鲟商品信息
     *
     * @param id
     * @return int
     */
    public AuctionItemModel getAuctionItemModel(String id) {
        //构造查询条件
        NativeSearchQuery query = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.matchPhraseQuery("id",id))
                .withSort(SortBuilders.fieldSort("createTime").order(SortOrder.DESC))
                .build();
        SearchHits<AuctionItemModel> searchHits = elasticsearchRestTemplate.search(query, AuctionItemModel.class, IndexCoordinates.of("auction_item"));
        try {
            AuctionItemModel auctionItemModel = searchHits.getSearchHits().get(0).getContent();
            return auctionItemModel;
        } catch (Exception e) {
            return null;
        }
    }




    public Map<String, String> searchByKey() {


        String topTime1 = timePrefix + " " + TIME_1;
        String topTime2 = timePrefix + " " + TIME_2;
        long num1 = LocalDateTime.parse(topTime1,DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")).toInstant(ZoneOffset.of("+8")).toEpochMilli();
        long num2 = LocalDateTime.parse(topTime2,DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")).minusDays(1).toInstant(ZoneOffset.of("+8")).toEpochMilli();
        long dd = num1 - num2;
        long lowTimeME0 = LocalDateTime.parse(topTime1, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")).toInstant(ZoneOffset.of("+8")).toEpochMilli() - dd;
        long topTimeEM1 = LocalDateTime.parse(topTime1, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")).toInstant(ZoneOffset.of("+8")).toEpochMilli();
        long topTimeEM2 = LocalDateTime.parse(topTime2, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")).toInstant(ZoneOffset.of("+8")).toEpochMilli();
        long nowEM = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();

        String tomorrowTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(lowTimeME0), ZoneId.systemDefault()).toString();
        String nowTime = LocalDateTime.now().toString();
        //查询搜索结果
        NativeSearchQuery query = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.rangeQuery("createTime").from(tomorrowTime).to(nowTime))
                .withSort(SortBuilders.fieldSort("createTime").order(SortOrder.DESC))
                .build();

        SearchHits<AuctionItemModel> searchHits = elasticsearchRestTemplate.search(query, AuctionItemModel.class, IndexCoordinates.of("auction_item"));
        Map<String, String> map = new HashMap<>();

        if (nowEM <= topTimeEM1) {
            for (int i = 0; i < searchHits.getSearchHits().size(); i++) {
                AuctionItemModel auctionItemModel = searchHits.getSearchHits().get(i).getContent();
                System.out.println(auctionItemModel.getCreateTime());
                long a = LocalDateTime.parse(auctionItemModel.getCreateTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")).toInstant(ZoneOffset.of("+8")).toEpochMilli();

                if (a < nowEM && a > lowTimeME0 && auctionItemModel.getDeleted().equals("0")) {
                    map.put("商品名:" + auctionItemModel.getName() +
                            "  商品信息:" + (auctionItemModel.getDescription() == null ? "" : auctionItemModel.getDescription()) +
                            "  起拍价(最低价):" + (auctionItemModel.getLowerPrice() == null ? "未知" : auctionItemModel.getLowerPrice()),
                            "    商品连接:" + getAuctionURL(auctionItemModel.getId()));

                }
            }
        } else if (nowEM < topTimeEM2) {
            for (int i = 0; i < searchHits.getSearchHits().size(); i++) {
                AuctionItemModel auctionItemModel = searchHits.getSearchHits().get(i).getContent();
                System.out.println(auctionItemModel.getCreateTime());
                long a = LocalDateTime.parse(auctionItemModel.getCreateTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")).toInstant(ZoneOffset.of("+8")).toEpochMilli();

                if (a < topTimeEM2 && a > topTimeEM1 && auctionItemModel.getDeleted().equals("0")) {
                    map.put("商品名:" + auctionItemModel.getName() +
                            "  商品信息:" + (auctionItemModel.getDescription() == null ? "" : auctionItemModel.getDescription()) +
                            "  起拍价(最低价):" + (auctionItemModel.getLowerPrice() == null ? "未知" : auctionItemModel.getLowerPrice()),
                            "    商品连接:" + getAuctionURL(auctionItemModel.getId()));

                }
            }
        } else {

        }
        return map;
    }



    //快开始拍卖时通知
    public Map<String,String > searchForNotify(){
        //查询所有即将拍卖的拍品
        String timeLow = timePrefix + "T" + TIME_LOW + ".000Z";
        String timeHigh = timePrefix + "T" + TIME_HIGH + ".000Z";

        List<AuctionItemModel> auctionItemModels = new ArrayList<>();



        long low = LocalDateTime.parse(timeLow, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")).toInstant(ZoneOffset.of("+8")).toEpochMilli();
        long high = LocalDateTime.parse(timeHigh, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")).toInstant(ZoneOffset.of("+8")).toEpochMilli();

        String lowTimeString = LocalDateTime.ofInstant(Instant.ofEpochMilli(low), ZoneId.systemDefault()).toString();
        String highTimeString = LocalDateTime.now().toString();

        NativeSearchQuery query = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.rangeQuery("createTime").from(lowTimeString).to(highTimeString))
                .withSort(SortBuilders.fieldSort("createTime").order(SortOrder.DESC))
                .build();

        SearchHits<AuctionRegisterEntity> searchHits = elasticsearchRestTemplate.search(query, AuctionRegisterEntity.class, IndexCoordinates.of("auction_register"));
        for (int i = 0; i < searchHits.getSearchHits().size(); i++) {
            String itemId = searchHits.getSearchHit(i).getContent().getItemId();

            NativeSearchQuery query1 = new NativeSearchQueryBuilder()
                    .withQuery(QueryBuilders.matchPhraseQuery("id", itemId))
                    .withSort(SortBuilders.fieldSort("createTime").order(SortOrder.DESC))
                    .build();
            SearchHits<AuctionItemModel> searchItemModelHits = elasticsearchRestTemplate.search(query1, AuctionItemModel.class, IndexCoordinates.of("auction_item"));
            auctionItemModels.add(searchItemModelHits.getSearchHit(0).getContent());
        }
        Map<String, String> map = new HashMap<>();

        String URI = HTTP_PREFIX + AUCTION_HOST + ":" + AUCTION_PORT + URI_PATH;
        for (int i = 0; i < auctionItemModels.size(); i++) {
            String url = URI + "?itemId=" + auctionItemModels.get(i).getId() + " | " + auctionItemModels.get(i).getId();
            map.put(("商品:《" + auctionItemModels.get(i).getName() + "》即将开始拍卖\n商品简介：" + auctionItemModels.get(i).getDescription()), url);
        }

        return map;
    }

    //拍卖结束时通知买家
    public Map<String ,String> searchForBuyer(){
        return null;
    }




    /**
     * 获取指定id的商品推广链接
     *
     * @param id
     * @return int
     */
    public String getAuctionURL(String id){
        String URI = HTTP_PREFIX + AUCTION_HOST + ":" + AUCTION_PORT + URI_PATH;
        String url = URI + "?itemId=" + id;
        return url;
    }


}